package cms.jason.web.controller;

import cms.jason.dao.TopImageDao;
import cms.jason.entity.TopImage;
import cms.jason.entity.TopImage_;
import com.cn.lotary.base.dao.BaseDao;
import com.cn.lotary.base.web.BaseController;
import com.cn.lotary.util.LoggerUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.metamodel.SingularAttribute;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Jason
 */
//TODO: order p:orderlist
@ManagedBean
@ViewScoped
public class TopImageController extends BaseController<TopImage> {

    @EJB
    private TopImageDao imageDao;

    @Override
    protected BaseDao<TopImage> dao() {
        return imageDao;
    }

    @Override
    protected SingularAttribute selectItemLabel() {
        return TopImage_.src;
    }
    private static final int BUFFER_SIZE = 6124;

    public List<TopImage> showImages() {
        return imageDao.getShowImages();
    }

    public void fileUploadMultiple(FileUploadEvent event) {
        //TODO:check picture size
        UploadedFile file = event.getFile();
        ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
        File result = new File(extContext.getRealPath("//upload") + "//" + file.getFileName());
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(result);
            byte[] buffer = new byte[BUFFER_SIZE];
            int bulk;
            InputStream inputStream = file.getInputstream();
            while (true) {
                bulk = inputStream.read(buffer);
                if (bulk < 0) {
                    break;
                }
                fileOutputStream.write(buffer, 0, bulk);
                fileOutputStream.flush();
            }
            fileOutputStream.close();
            inputStream.close();
            FacesMessage msg = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
            System.out.println("Succesful " + file.getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            TopImage topImage = new TopImage();
            topImage.setSrc("/upload/" + file.getFileName());
            imageDao.create(topImage);
        } catch (IOException e) {
            LoggerUtils.error(e);
            FacesMessage error = new FacesMessage("The files were not uploaded!");
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }
}
